package com.iwdnb.gkgz.infrastructure.dao.repo.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;

import cn.hutool.core.date.DateUtil;
import com.iwdnb.bmnf.common.exception.ExceptionsEnhancer;
import com.iwdnb.bmnf.common.service.CacheService;
import com.iwdnb.bmnf.common.utils.BeanConvertUtils;
import com.iwdnb.gkgz.common.constant.CacheConstants;
import com.iwdnb.gkgz.common.model.dto.StockCandleDTO;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.common.utils.CandleDataBuilder;
import com.iwdnb.gkgz.common.utils.RealtimeStockUtils;
import com.iwdnb.gkgz.common.utils.StockRangeUtils;
import com.iwdnb.gkgz.common.utils.StockUtils;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockDayDataRepository;
import com.iwdnb.wwzy.dao.MetaDataDAO;
import com.iwdnb.wwzy.model.query.MetaQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import static com.iwdnb.gkgz.common.constant.GkgzConstants.OBJECT_CODE_STOCK_CANDLE;
import static com.iwdnb.gkgz.common.utils.DateUtils.afterOrEquals;
import static com.iwdnb.gkgz.common.utils.DateUtils.beforeOrEquals;

/**
 * 使用本地存储时,设置gkgz.db.storeType=local
 */
//@Component
@ConditionalOnProperty(prefix = "gkgz.db", name = "storeType", havingValue = "db", matchIfMissing = true)
//@Primary
public class StockDayDataRepositoryImpl implements StockDayDataRepository {
    @Autowired
    private MetaDataDAO metaDataDAO;
    @Autowired
    private CacheService cacheService;

    @Override
    public StockDayData queryDate(String code, String date) {
        List<StockDayData> stockDayDataList = queryAll(code);
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return null;
        }
        return stockDayDataList.stream().filter(stockDayData -> stockDayData.getDate().equals(date)).findAny().orElse(
            null);
    }

    @Override
    public List<StockDayData> queryAllByDateAfter(String code, String date) {
        List<StockDayData> stockDayDataList = queryAll(code);
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return null;
        }
        Date end = DateUtil.endOfDay(DateUtil.parseDate(date));
        return stockDayDataList.stream().filter(stockDayData -> {
            Date d = DateUtil.parseDate(stockDayData.getDate());
            return afterOrEquals(d, end);
        }).collect(Collectors.toList());
    }

    @Override
    public List<StockDayData> queryAllByDateRange(String code, String startDate, String endDate) {
        List<StockDayData> stockDayDataList = queryAll(code);
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return null;
        }
        Date begin = DateUtil.parseDate(startDate);
        Date end = DateUtil.parseDate(endDate);
        return stockDayDataList.stream().filter(stockDayData -> {
            Date date = DateUtil.parseDate(stockDayData.getDate());
            return afterOrEquals(date, begin) && beforeOrEquals(date, end);
        }).collect(Collectors.toList());

    }

    @Override
    public List<StockDayData> queryAllBeforeDate(String code, String endDate) {
        List<StockDayData> stockDayDataList = queryAll(code);
        Date end = DateUtil.endOfDay(DateUtil.parseDate(endDate));
        return stockDayDataList.stream().filter(stockDayData -> {
            Date date = DateUtil.parseDate(stockDayData.getDate());
            return beforeOrEquals(date, end);
        }).collect(Collectors.toList());
    }

    @Override
    public List<StockDayData> queryAllByYear(String code, String year) {
        return queryAllByDateRange(code, year + "-01-01", year + "-12-31");
    }

    @Override
    public void save(String code, StockDayData stockDayData) {
        List<StockDayData> stockDayDataList = queryAll(code);
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return;
        }
        stockDayData.setFenshiList(null);
        StockDayData temp = StockUtils.getStockDayData(stockDayDataList, stockDayData.getDate());
        if (Objects.isNull(temp)) {
            stockDayDataList.add(stockDayData);
        } else {
            BeanConvertUtils.copyProperties(stockDayData, temp);
        }
        saveAll(code, stockDayDataList);
    }

    @Override
    public void deleteByDateAfterAndDateBefore(Date startDate, Date endDate) {
        ExceptionsEnhancer.createError("not support");
    }

    @Override
    public void saveAll(String code, List<StockDayData> stockDayDataList) {
        StockUtils.sortStockDayDataList(stockDayDataList);
        String candleData = CandleDataBuilder.dayDataToCandle(stockDayDataList);
        StockCandleDTO stockCandleDTO = getStockCandle(code);
        Boolean existFlag = true;
        if (Objects.isNull(stockCandleDTO)) {
            stockCandleDTO = new StockCandleDTO();
            existFlag = false;
        }
        stockCandleDTO.setCode(code);
        stockCandleDTO.setCandleData(candleData);
        String rangeData = JSON.toJSONString(StockRangeUtils.calculateStockRange(stockDayDataList));
        stockCandleDTO.setRangeData(rangeData);
        if (existFlag) {
            metaDataDAO.update(OBJECT_CODE_STOCK_CANDLE, stockCandleDTO);
        } else {
            metaDataDAO.insert(OBJECT_CODE_STOCK_CANDLE, stockCandleDTO);
        }
    }

    private StockCandleDTO getStockCandle(String code) {
        MetaQuery metaQuery = new MetaQuery();
        metaQuery.addParam("code", code);
        return metaDataDAO.get(OBJECT_CODE_STOCK_CANDLE, metaQuery, StockCandleDTO.class);
    }

    @Override
    public List<StockDayData> queryAll(String code) {
        StockCandleDTO stockCandleDTO = getStockCandle(code);
        if (Objects.isNull(stockCandleDTO)) {
            return null;
        }
        List<StockDayData> stockDayDataList = CandleDataBuilder.candleToDayData(stockCandleDTO.getCandleData());
        //实时更新今日数据
        String date = DateUtil.formatDate(new Date());
        StockDayData cacheTodayData = RealtimeStockUtils.getRealtimeData(code);
        if (Objects.nonNull(cacheTodayData)) {
            StockDayData todayData = StockUtils.getStockDayData(stockDayDataList, date);
            if (Objects.isNull(todayData)) {
                stockDayDataList.add(cacheTodayData);
            } else {
                BeanConvertUtils.copyProperties(cacheTodayData, todayData);
            }
        }
        for(StockDayData stockDayData:stockDayDataList){
            stockDayData.setCode(code);
        }
        StockUtils.calculateStockRange(stockDayDataList);
        return stockDayDataList;
    }

}
